import 'package:floor/floor.dart';
import 'dart:async';
import 'package:sqflite/sqflite.dart' as sqflite;
import 'package:flutter_demo/ui/db/floor/dao/memo_dao.dart';
import 'package:flutter_demo/ui/db/floor/entity/memo.dart';
import 'package:flutter_demo/ui/db/floor/converter/string_list_converter.dart';

part 'database.g.dart';


///flutter packages pub run build_runner build  命令生成  database.g.dart 文件

@TypeConverters([StringListConverter, DateTimeConverter])
@Database(version: 1, entities: [Memo])
abstract class AppDatabase extends FloorDatabase {
  MemoDao get memoDao;
}


class DBUtil {
  DBUtil._();

  ///单例
  static DBUtil? _singleton;

  factory DBUtil() => _singleton ??= DBUtil._();

  /// 释放单例
  void dispose() => _singleton = null;

  ///定义数据库变量
  late final AppDatabase _db;

  MemoDao get memoDao => _db.memoDao;

  initDB() async {
    _db = await $FloorAppDatabase
        .databaseBuilder('app_database.db')
        .addMigrations([migration1to2])
        .build();
  }

  ///数据库升级
  final migration1to2 = Migration(1, 2, (database) async {
    await database.execute('ALTER TABLE Memo ADD COLUMN category TEXT');

    /// 可选，设置旧版本字段初始值
    await database.update('Memo', {'category': ''});
  });
}
